package com.iot08.api.service;

import com.iot08.common.entity.app.DeviceSingleChatGroup;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author cwj
 * @description
 * @date 2025/7/6 15:37
 **/
@Slf4j
@Service
public class DeviceSingleChatGroupService extends BaseService<DeviceSingleChatGroup> {


    /**
     * @description 创建设备群组
     * @author cwj
     * @param [imei1, imei2]
     * @return void
     * @date @time 2025/7/7 12:00
     **/
    public void createDeviceSingleGroup(String imei1, String imei2) {
        //比较两个IMEI大小，小的imei在前
        String id = imei1.compareTo(imei2) < 0?(imei1 + "&" + imei2):(imei2 + "&" + imei1);
        //创建设备跟设备的单聊群，不存在则创建
        DeviceSingleChatGroup deviceSingleChatGroup = this.findById(id);
        if(ObjectUtils.isEmpty(deviceSingleChatGroup)) {
            deviceSingleChatGroup = new DeviceSingleChatGroup();
            deviceSingleChatGroup.setId(id);
            deviceSingleChatGroup.setTimestamp(DateUtil.nowTimestampToDouble());
            deviceSingleChatGroup.setCreateTime(new Date());
            this.save(deviceSingleChatGroup);
        }
    }
    
    /**
     * @description 保存设备单聊群组消息
     * @author cwj
     * @param [imei1, imei2]
     * @return void
     * @date @time 2025/7/7 17:49
     **/
    public void saveDeviceSingleGroup(String imei1, String imei2) {
        DeviceSingleChatGroup deviceSingleChatGroup = new DeviceSingleChatGroup();
        deviceSingleChatGroup.setId(imei1.compareTo(imei2) < 0?(imei1 + "&" + imei2):(imei2 + "&" + imei1));
        deviceSingleChatGroup.setTimestamp(DateUtil.nowTimestampToDouble());
        deviceSingleChatGroup.setCreateTime(new Date());
        this.save(deviceSingleChatGroup);
    }


    /**
     * @description 删除设备
     * @author cwj
     * @param [imei1, imei2]
     * @return void
     * @date @time 2025/7/7 11:56
     **/
    public void delDataByImei(String imei1,String imei2) {
        String id = imei1.compareTo(imei2) < 0?(imei1 + "&" + imei2):(imei2 + "&" + imei1);
        DeviceSingleChatGroup deviceSingleChatGroup = this.findById(id);
        if(ObjectUtils.isNotEmpty(deviceSingleChatGroup)) {
            this.delById(id);
        }
    }

}
